package com.hthy.futures.base;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.google.gson.Gson;
import com.hthy.futures.AppContext;
import com.hthy.futures.R;
import com.hthy.futures.api.ST_TradeApi;
import com.hthy.futures.bean.Login;
import com.hthy.futures.ui.activity.LoginActivity;
import com.hthy.futures.utils.LogUtils;
import com.hthy.futures.utils.StringUtils;
import com.hthy.futures.utils.TDevice;
import com.hthy.futures.utils.ToastUtil;
import com.hthy.futures.view.ColorDialog;
import com.vilyever.socketclient.SocketClient;
import com.vilyever.socketclient.helper.SocketClientDelegate;
import com.vilyever.socketclient.helper.SocketPacket;
import com.vilyever.socketclient.helper.SocketResponsePacket;

import butterknife.ButterKnife;

/**
 * Fragment基础类
 */

@SuppressWarnings("WeakerAccess")
public abstract class BaseFragment extends Fragment implements SocketClientDelegate {
    protected View mRoot;
    protected Bundle mBundle;
    protected SocketClient socketClient;
    public boolean isReconNect = false;
    private ColorDialog mDialog;


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBundle = getArguments();
        initBundle(mBundle);


        socketClient = ((AppContext) getActivity().getApplication()).getSocketClient();
        socketClient.registerSocketClientDelegate(this);
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (mRoot != null) {
            ViewGroup parent = (ViewGroup) mRoot.getParent();
            if (parent != null)
                parent.removeView(mRoot);
        } else {
            mRoot = inflater.inflate(getLayoutId(), container, false);
            // Do something
            onBindViewBefore(mRoot);
            // Bind view
            ButterKnife.bind(this, mRoot);
            // Get savedInstanceState
            if (savedInstanceState != null)
                onRestartInstance(savedInstanceState);
            // Init
            initWidget(mRoot);
            initData();
        }
        return mRoot;
    }

    protected void onBindViewBefore(View root) {
        // ...
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        ButterKnife.unbind(this);
        mBundle = null;

        if (socketClient != null) {
            socketClient.removeSocketClientDelegate(this);
        }
    }

    protected int getLayoutId() {
        return 0;
    }

    ;

    protected void initBundle(Bundle bundle) {

    }

    protected void initWidget(View root) {

    }

    protected void initData() {

    }

    // 可以直接替代 bind
    protected <T extends View> T findView(int viewId) {
        return (T) mRoot.findViewById(viewId);
    }

    protected void onRestartInstance(Bundle bundle) {

    }

    protected void showToast(String msg) {
        //Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
        ToastUtil.show(msg);
    }

    protected void showToast(int msg) {
        //Toast.makeText(getActivity(), getActivity().getString(msg), Toast.LENGTH_SHORT).show();
        ToastUtil.show(msg);
    }

    @Override
    public void onConnected(SocketClient client) {
        LogUtils.e("connect");
        SocketPacket packet = socketClient.sendData(new byte[]{0x02}); // 发送消息
        //packet = socketClient.sendString("sy hi!"); // 发送消息
        // 必须得加这一句话，不然没效果
        socketClient.cancelSend(packet); // 取消发送，若在等待发送队列中则从队列中移除，若已发送完成则无法取消，若正在发送且分段发送则取消发送剩余数据（此时若没有设置包头用于远程端判断下一个信息包的开始可能出现粘包或数据不全问题）

        if (isReconNect) {
            socketClient.sendData(ST_TradeApi.login(AppContext.account, AppContext.accountPwd));
        }

    }

    @Override
    public void onDisconnected(SocketClient client) {
        isReconNect = true;
        // 断开连接回调，可在此实现自动重连
        // socketClient.connect();

        // 需要重新赋值id
        showNetDisDialog();

    }

    @Override
    public void onResponse(SocketClient client, @NonNull SocketResponsePacket responsePacket) {
        /*
        *     V0.1000000730000302700000000000000000{
               "9001" : "0",
               "9002" : ""
               }*/
        // 如果是返回3027的返回的话，说明是别人登录的，否则就是网络断线的问题
        String message2 = responsePacket.getMessage(); // 获取按默认设置的编码转化的String，可能为null
        LogUtils.d(message2);
        if (message2.indexOf("3027") != -1) {
            showLogoutDialog();
            // 还应该释放资源
            /*socketClient.removeSocketClientDelegate(this);
            socketClient.disconnect();
            socketClient = null;*/
            return;
        }
        if (isReconNect) {
            String message = responsePacket.getMessage(); // 获取按默认设置的编码转化的String，可能为null
            LogUtils.e(message);

            // 然后接着从返回的数据中截掉前面的37位，剩下就是json字符串内容。
            String substring = message.substring(37);
            Gson gson = new Gson();
            Login login = gson.fromJson(substring, Login.class);
            AppContext.accountId = Integer.parseInt(login.get_$1());
            AppContext.sessionId = login.get_$336();
            AppContext.accountName = login.get_$9103();
            LogUtils.e("我是断线后登陆页面里面的方法" + "accId:" + login.get_$1() + "&&&&ssetionId" + login.get_$336());

            isReconNect = false;
        }
        String responMes = responsePacket.getMessage();
        byte[] data = responsePacket.getData(); // 获取接收的byte数组，不为null
        if (data.length < 37) {
            return;
        }
        byte[] bytes = StringUtils.subBytes(data, 37, data.length - 37);
        onResponse(client, responMes, bytes);
    }

    /**
     * 简写版本的onResponse
     *
     * @param client    之所以保留这个，可能通过它来发送以请求其它数据
     * @param responMes 通过它可以判断返回的数据是否包含某个关键词
     * @param subBytes  经过截取后的的byte[] 数据
     */
    protected void onResponse(SocketClient client, String responMes, byte[] subBytes) {

    }

    private void showLogoutDialog() {
        if (mDialog == null) {
            mDialog = new ColorDialog(getActivity());
        }
        mDialog.setColor("#8ECB54");
        mDialog.setAnimationEnable(true);
        mDialog.setTitle(getString(R.string.operation));
        mDialog.setContentText(R.string.please_login);
        mDialog.setPositiveListener(getString(R.string.text_iknow), new ColorDialog.OnPositiveListener() {
            @Override
            public void onClick(ColorDialog dialog) {
                //Toast.makeText(getActivity(), dialog.getPositiveText().toString(), Toast.LENGTH_SHORT).show();
                mDialog.dismiss();
                startActivity(new Intent(getActivity(), LoginActivity.class));
                // EventBus.getDefault().post(new LoginEvent(true));
                getActivity().finish();
            }
        }).show();
    }

    public void showColorDialog(String tip) {
        if (mDialog == null) {
            mDialog = new ColorDialog(getActivity());
        }
        mDialog.setColor("#8ECB54");
        mDialog.setAnimationEnable(true);
        mDialog.setTitle(getString(R.string.operation));
        mDialog.setContentText(tip);
        mDialog.setPositiveListener(getString(R.string.text_iknow), new ColorDialog.OnPositiveListener() {
            @Override
            public void onClick(ColorDialog dialog) {
                //Toast.makeText(getActivity(), dialog.getPositiveText().toString(), Toast.LENGTH_SHORT).show();
                mDialog.dismiss();
            }
        }).show();
    }

    private void showNetDisDialog() {
        if (mDialog == null) {
            mDialog = new ColorDialog(getActivity());
        }
        mDialog.setColor("#8ECB54");
        mDialog.setAnimationEnable(true);
        mDialog.setTitle(getString(R.string.operation));
        if (!TDevice.hasInternet()) {
            mDialog.setContentText(R.string.please_checknet_login);
        }else {
            mDialog.setContentText("******");
        }
        mDialog.setPositiveListener(getString(R.string.text_iknow), new ColorDialog.OnPositiveListener() {
            @Override
            public void onClick(ColorDialog dialog) {
                //Toast.makeText(getActivity(), dialog.getPositiveText().toString(), Toast.LENGTH_SHORT).show();
                mDialog.dismiss();
                startActivity(new Intent(getActivity(), LoginActivity.class));
                getActivity().finish();
            }
        }).show();
    }
}
